package org.jsola.hr.common;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lyh
 */
public class BeanCopyUtil {
    private static final Mapper MAPPER = DozerBeanMapperBuilder.buildDefault();


    /**
     * 普通Bean复制
     * @param source 原始类
     * @param clazz 需要copy到此类
     * @param <T> 泛型类型参数
     * @param <D> 泛型类型参数
     * @return copy
     */
    public static <T, D> D beanCopy(T source, Class<D> clazz) {
        if (source == null) {
            return null;
        }
        return MAPPER.map(source, clazz);
    }

    /**
     * 集合对象复制
     * @param source 元类型
     * @param clazz 需要copy到此类
     * @param <T> 泛型类型参数
     * @param <D> 泛型类型参数
     * @return copy
     */
    public static <T, D> List<D> beanListCopy(List<T> source, Class<D> clazz) {
        List<D> list = new ArrayList<D>();
        if (!CollectionUtils.isEmpty(source)) {
            for (T t : source) {
                D d = MAPPER.map(t, clazz);
                list.add(d);
            }
        }
        return list;
    }

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }


}
